package br.com.management.mentor.model.repositories;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import br.com.management.mentor.model.entities.auth.Permission;
import br.com.management.mentor.model.entities.auth.QPermission;

import com.mysema.query.jpa.impl.JPAQuery;

@Component
@Repository
public class PermissionsRepository {

	private QPermission qPermission = QPermission.permission;

	@Autowired
	private EntityManagerFactory emf;

	public Permission getByName( String name ) {
		EntityManager em = emf.createEntityManager();
		try {
			JPAQuery query = new JPAQuery( em );
			return query.from( qPermission ).where( qPermission.name.eq( name ) ).uniqueResult( qPermission );
		} finally {
			if ( em != null ) em.close();
		}
	}

	public List<Permission> getAll() {
		EntityManager em = emf.createEntityManager();
		try {
			JPAQuery query = new JPAQuery( em );
			return query.from( qPermission ).where( qPermission.name.notEqualsIgnoreCase( "ROLE_USER" ) ).orderBy( qPermission.name.asc() ).list( qPermission );
		} finally {
			if ( em != null ) em.close();
		}
	}

	public Permission getDefault() {
		EntityManager em = emf.createEntityManager();
		try {
			JPAQuery query = new JPAQuery( em );
			return query.from( qPermission ).where( qPermission.name.eq( "ROLE_USER" ) ).uniqueResult( qPermission );
		} finally {
			if ( em != null ) em.close();
		}
	}
	
 }